package com.spsoft.core.validation;

import com.spsoft.core.annotation.EnumValue;
import com.spsoft.core.utils.StringUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 *  对注解EnumValue 验证类
 * @author: cdl
 * @create: 2022/6/30 12:55
 **/
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {

    private String[] strValues;
    private int[] intValues;
    private Class<? extends Enum<?>> clazz;
    private String fieldValue;

    @Override
    public void initialize(EnumValue constraintAnnotation) {
        strValues = constraintAnnotation.strValues();
        intValues = constraintAnnotation.intValues();

    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null || StringUtil.isBlank(value.toString())) {
            return true;
        }
        if (value instanceof String) {
            for (String s : strValues) {
                if (s.equals(value)) {
                    return true;
                }
            }
        } else if (value instanceof Integer) {
            for (Integer s : intValues) {
                if (s == value) {
                    return true;
                }
            }
        }
        return false;
    }
}
